<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../store/user'
import { getUserOrders } from '../../api/user'
import { showToast } from 'vant'

const router = useRouter()
const userStore = useUserStore()

// 用户订单列表
const orderList = ref<any[]>([])
// 加载状态
const loading = ref(false)
// 下拉刷新
const refreshing = ref(false)

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '未知';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 计算订单状态
const getOrderStatus = (order: any) => {
  // 如果没有支付记录，则为待支付
  if (!order.payments || order.payments.length === 0) {
    return { text: '待支付', color: '#ff976a' };
  }
  
  const now = new Date();
  const checkOutDate = order.checkOutDate ? new Date(order.checkOutDate) : null;
  
  if (checkOutDate && now > checkOutDate) {
    return { text: '已完成', color: '#07c160' };
  }
  
  return { text: '已确认', color: '#1989fa' };
};

// 获取用户订单
const fetchUserOrders = async () => {
  try {
    if (!userStore.userId) {
      showToast('获取用户ID失败');
      return;
    }
    
    loading.value = true;
    const res = await getUserOrders(userStore.userId);
    orderList.value = res.data || [];
  } catch (error: any) {
    showToast(error.message || '获取订单失败');
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 计算入住天数
const calculateDays = (checkIn: string, checkOut: string) => {
  if (!checkIn || !checkOut) return 1;
  
  const start = new Date(checkIn);
  const end = new Date(checkOut);
  const diffTime = Math.abs(end.getTime() - start.getTime());
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  
  return diffDays || 1;
};

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true;
  fetchUserOrders();
};

// 查看订单详情
const viewOrderDetail = (id: string) => {
  router.push(`/order/detail/${id}`);
};

// 页面初始化
onMounted(() => {
  fetchUserOrders();
});
</script>

<template>
  <div class="order-list-container">
    <van-nav-bar 
      title="我的订单" 
      left-arrow 
      @click-left="router.back()" 
    />
    
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <div class="content">
        <van-loading v-if="loading" class="loading-spinner" type="spinner" color="#1989fa" />
        
        <div v-else-if="orderList.length > 0" class="order-cards">
          <div 
            v-for="order in orderList" 
            :key="order.orderID || order.id" 
            class="order-card"
            @click="viewOrderDetail(order.orderID || order.id)"
          >
            <div class="order-header">
              <span class="order-id">订单号: {{ order.orderID || order.id }}</span>
              <span 
                class="order-status" 
                :style="{ color: getOrderStatus(order).color }"
              >
                {{ getOrderStatus(order).text }}
              </span>
            </div>
            
            <div class="order-content">
              <div class="room-info">
                <div class="room-type">{{ order.room?.roomType || '标准间' }}</div>
                <div class="hotel-name">{{ order.hotelName || '酒店名称' }}</div>
              </div>
              
              <div class="date-info">
                <div class="date-range">
                  <span class="date">{{ formatDate(order.checkInDate) }}</span>
                  <span class="separator">至</span>
                  <span class="date">{{ formatDate(order.checkOutDate) }}</span>
                </div>
                <div class="stay-days">共{{ calculateDays(order.checkInDate, order.checkOutDate) }}晚</div>
              </div>
              
              <div class="price-info">
                <span class="price">¥{{ order.room?.price || 0 }}</span>
                <span class="unit">/晚</span>
              </div>
            </div>
            
            <div class="order-footer">
              <van-button 
                size="small" 
                type="primary" 
                plain
                class="detail-btn"
              >查看详情</van-button>
            </div>
          </div>
        </div>
        
        <van-empty v-else description="暂无订单" />
      </div>
    </van-pull-refresh>
  </div>
</template>

<style scoped>
.order-list-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 50px;
}

.content {
  padding: 12px;
}

.loading-spinner {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.order-cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.order-card {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(100, 101, 102, 0.08);
  position: relative;
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f5f5f5;
}

.order-id {
  font-size: 14px;
  color: #646566;
}

.order-status {
  font-size: 14px;
  font-weight: 500;
}

.order-content {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.room-info {
  flex: 1;
}

.room-type {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 4px;
}

.hotel-name {
  font-size: 14px;
  color: #646566;
}

.date-info {
  flex: 1;
  text-align: center;
}

.date-range {
  font-size: 14px;
  margin-bottom: 4px;
}

.date {
  color: #323233;
}

.separator {
  color: #969799;
  padding: 0 4px;
}

.stay-days {
  font-size: 12px;
  color: #969799;
}

.price-info {
  text-align: right;
  flex: 0.5;
}

.price {
  font-size: 18px;
  font-weight: bold;
  color: #ee0a24;
}

.unit {
  font-size: 12px;
  color: #969799;
}

.order-footer {
  display: flex;
  justify-content: flex-end;
}

.detail-btn {
  border-radius: 16px;
}
</style> 